package com.sen.design.pattern.creational.singleton;

/**
 * 双重检查锁(面试常用)
 */
public class LazyDoubleCheckSingleton {
    // 1、加volatile关键字禁止重排序，保证线程安全
    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton;
    private LazyDoubleCheckSingleton(){}
    public static LazyDoubleCheckSingleton getInstance(){

        // 先判断是否为空
        if (lazyDoubleCheckSingleton == null){
            //再使用同步关键字保证线程安全
            synchronized (LazyDoubleCheckSingleton.class){
                // 第二次检查
                if (lazyDoubleCheckSingleton == null){
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton();
                }
            }
        }
        return lazyDoubleCheckSingleton;
    }
}
